package com.e2j.utils.json;

import java.io.*;

/**
 * fastjson读取文件基类
 * @author 杨永良
 * @date 2020/9/17 14:27
 **/
public class JsonFileData extends BaseJsonData implements IJsonData {



    /**
     * 读取json文件成为Hashmap
     * 使用：先创建类读取文件，然后用getMap
     *
     * @param fileName  资源文件目录的文件名或绝对路径的文件名,当资源文件找不到会把参数视为绝对路径打开
     * @throws IOException IO异常
     */
    public JsonFileData(String fileName) throws IOException {
        BufferedReader reader;
        //先尝试资源文件目录打开
        InputStream is = JsonHashMapReader.class.getClassLoader().getResourceAsStream(fileName);
        if (is == null) {
            //资源文件没用则用绝对路径打开
            File file = new File(fileName);
            if (file.isFile() && file.exists()) {
                FileInputStream fis = new FileInputStream(file);
                reader = new BufferedReader(new InputStreamReader(fis));
                uri = file.getPath();
            } else {
                throw new IOException("Json读取配置文件错误，没有找到文件"+fileName);
            }
        } else {
            reader = new BufferedReader(new InputStreamReader(is));
        }

        String line;
        StringBuffer sb = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        jsonStr = sb.toString();
        String filenameTemp = fileName.replace("\\","/");
        String[] filenameParts = filenameTemp.split("/");
        if(filenameParts.length>1){
            filenameTemp = filenameParts[filenameParts.length-1];
        }
        this.fileName = filenameTemp;
        md5 = getMD5(jsonStr);
        fileSize = jsonStr.length();
    }



}
